<?php
// +----------------------------------------------------------------------
// | INPHP
// | Copyright (c) 2023 https://inphp.cc All rights reserved.
// | Licensed ( https://opensource.org/licenses/MIT )
// | Author: 幺月儿(https://gitee.com/lulanyin) Email: inphp@qq.com
// +----------------------------------------------------------------------
// | 日志处理
// +----------------------------------------------------------------------
namespace Inphp\Core\Util;

use Exception;
use Inphp\Core\Service;

class Log
{
    /**
     * 往日志文件末尾写内容
     * @param string $file
     * @param string|Exception $content
     * @param bool $output
     */
    public static function writeToEnd(string $file, string|Exception $content, bool $output = false): void
    {
        $dir = substr($file, 0, strripos($file, "/"));
        if (is_dir($dir) || mkdir($dir, 0777, true)) {
            if ($f = fopen($file, "a")) {
                if (!is_string($content)) {
                    $data = [
                        "code: ".$content->getCode(),
                        "file: ".$content->getFile(),
                        "line: ".$content->getLine(),
                        "message: ".$content->getMessage(),
                        "trace: \r\n".$content->getTraceAsString()
                    ];
                    $content = date("Y/m/d H:i:s")."\r\n".join("\r\n", $data);
                }
                fwrite($f, $content."\r\n");
                fclose($f);
                if ($output) {
                    self::output($content);
                }
            }
        }
    }

    /**
     * 日志内容直接覆盖到某个文件
     * @param string $file
     * @param string|Exception $content
     */
    public static function save(string $file, string|Exception $content): void
    {
        $dir = substr($file, 0, strripos($file, "/"));
        if (is_dir($dir) || mkdir($dir, 0777, true)) {
            if (is_string($content)) {
                file_put_contents($file, $content."\r\n");
            } else {
                $data = [
                    "code: ".$content->getCode(),
                    "file: ".$content->getFile(),
                    "line: ".$content->getLine(),
                    "message: ".$content->getMessage(),
                    "trace: \r\n".$content->getTraceAsString()
                ];
                file_put_contents($file, join("\r\n", $data)."\r\n");
            }
        }
    }

    /**
     * 输出内容
     * @param string $context
     * @param bool $output
     */
    public static function output(string $context, bool $output = true): void
    {
        if ($output) {
            echo $context.PHP_EOL;
        }
    }
}